﻿using Newtonsoft.Json;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Reflection;

namespace MuXue.Zyiz.Template.Common.RabbitMQ
{
    public class RabbitMQBusiness
    {
        /// <summary>
        /// 临时存储,防止一直使用反射,浪费性能.
        /// </summary>
        private static ConcurrentDictionary<String, Object> FunDic = new ConcurrentDictionary<String, Object>();
        public bool BusinessDo(string message)
        {
            RabbitMQ_SendModel jsondata = JsonConvert.DeserializeObject<RabbitMQ_SendModel>(message);
            bool res = true;
            try
            {
                if (FunDic.ContainsKey(jsondata.customerClass))
                {
                    IRabbitMQConsumer consumer1 = FunDic[jsondata.customerClass] as IRabbitMQConsumer;
                    consumer1?.Consume(jsondata.senddata);
                }
                else
                {
                    string strClass = jsondata.customerClass;           // 命名空间+类名
                    string strMethod = jsondata.customerMethod;        // 方法名                
                    Type type = Assembly.Load(jsondata.CustomerAssembly).GetType(strClass); // 存储类  通过类名获取同名类
                    var consumer = RabbitMQHelper.ServiceProvider.GetService(type) as IRabbitMQConsumer;
                    FunDic.AddOrUpdate(strClass, consumer, (key, obj) =>
                    {
                        LogHelper.Info("RabbitMQBusiness add new Object, type is " + jsondata.customerClass);
                        return consumer;
                    });
                    consumer?.Consume(jsondata.senddata);
                }
                //Object obj = Activator.CreateInstance(type); // 存储类的实例 创建实例
                //// 注意获取重载方法，需要指定参数类型
                //MethodInfo method = type.GetMethod(strMethod, new Type[] { typeof(string) });      // 获取方法信息
                //object[] parameters = new object[] { jsondata.senddata };
                //method.Invoke(obj, parameters);
                LogHelper.Info("receiver 消费者消费消息完成 do---  " + message);
                res = true;
            }
            catch (Exception e)
            {
                LogHelper.Info("receiver error---  " + message, e);
                res = false;
            }
            return res;
        }
    }
}
